import { computed, watch } from "vue";
import { GlobalThemeOverrides } from "naive-ui";
import { useLayoutStore } from "@/store/modules/layout";

export function useTheme() {
  const layoutStore = useLayoutStore();

  const themeOverrides = computed<GlobalThemeOverrides>(() => {
    const { primaryColor } = layoutStore.layout;
    return {
      common: {
        primaryColor: primaryColor,
        primaryColorHover: adjustColor(primaryColor, 0.1),
        primaryColorPressed: adjustColor(primaryColor, -0.1),
        primaryColorSuppl: adjustColor(primaryColor, 0.05),
      },
      Button: {
        colorPrimary: primaryColor,
        colorHoverPrimary: adjustColor(primaryColor, 0.1),
        colorPressedPrimary: adjustColor(primaryColor, -0.1),
      },
    };
  });

  // 监听主题色变化并更新 CSS 变量
  watch(
    () => layoutStore.layout.primaryColor,
    (color) => {
      if (color) {
        document.documentElement.style.setProperty("--primary-color", color);
      }
    },
    { immediate: true }
  );

  return {
    themeOverrides,
  };
}

// 调整颜色明度
function adjustColor(color: string | undefined, amount: number): string {
  if (!color) return "#1890ff"; // 返回默认颜色

  const clamp = (num: number) => Math.min(Math.max(num, 0), 255);

  // 移除 # 号
  const hex = color.replace("#", "");

  // 转换为 RGB
  const num = parseInt(hex, 16);
  const r = clamp(((num >> 16) + Math.round(amount * 255)) & 255);
  const g = clamp((((num >> 8) & 255) + Math.round(amount * 255)) & 255);
  const b = clamp(((num & 255) + Math.round(amount * 255)) & 255);

  // 转回 hex
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
